<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2019/1/10
 * Time: 14:54
 */

namespace api\storage\service;


use think\Collection;
use think\Model;

class BaseService
{

    /**
     * 进行json解析
     *
     * @param $str
     * @return mixed
     */
    public function jsonDecode($str)
    {
        if (is_array($str)) {
            return $str;
        }
        return json_decode($str, true);
    }

    /**
     * 判断对象不是空值
     *
     * @param $data
     * @return bool
     */
    public function isNotEmpty($data)
    {
        return !$this->isEmpty($data);
    }

    /**
     * 判断是不是空值
     *
     * @param $data
     * @return bool
     */
    public function isEmpty($data)
    {
        if ($data instanceof Collection) {
            return $data->isEmpty();
        } elseif ($data instanceof Model) {
            return $data == null || empty($data->getData());
        } else {
            return empty($data);
        }
    }

    public function now()
    {
        return date('y-M-d H:i:s', time());
    }

    /**
     * 对数组进行keyValue 装换
     *
     * @param array $arr
     * @param string $keyword
     * @param bool $isOverride
     * @return array
     */
    public function makeKeyValueArray($arr = [], $keyword = '', $isOverride = true)
    {
        $res = [];
        if ($this->isEmpty($arr)) {
            return $res;
        }

        foreach ($arr as $key => $value) {
            //如果相同的keyword，不进行覆盖的话。有相同值选择跳过。
            if ($isOverride == false) {
                if (!isset($res[$value[$keyword]])) {
                    $res[$value[$keyword]] = $value;
                }
            } else {
                $res[$value[$keyword]] = $value;
            }
        }
        return $res;
    }

    /**
     * 返回通用的模板
     *
     * @param int $status
     * @param array $data
     * @return array
     */
    public function resultTemplate($status = 0, $data = [])
    {
        return [
            'status' => $status,
            'data' => $data
        ];
    }


    /**
     * 将下划线命名转换为驼峰式命名
     *
     * @param $str
     * @param bool $ucfirst
     * @return mixed|string
     */
    protected function convertUnderline($str , $ucfirst = false)
    {
        $str = ucwords(str_replace('_', ' ', $str));
        $str = str_replace(' ','',lcfirst($str));
        return $ucfirst ? ucfirst($str) : $str;
    }

    protected function convertResult(array $data){
        $result = [];
        foreach ($data as $key=>$value) {
            foreach ($value as $oldK=>$v){
                $newK = $this->convertUnderline($oldK);
                $result[$key][$newK] = $v;
            }
        }
        return $result;
    }



}